package com.ts.api.module.channel.service.impl;

import com.gitee.apanlh.util.valid.ValidParam;
import com.ts.api.common.constant.channel.ChannelTypeEnum;
import com.ts.api.common.constant.common.SwitchEnum;
import com.ts.api.common.context.ChannelContext;
import com.ts.api.common.context.ChannelRequestContext;
import com.ts.api.common.localcache.DistrictCache;
import com.ts.api.module.channel.dao.ChannelConfigDao;
import com.ts.api.module.channel.dao.ChannelConfigIpOffModuleDao;
import com.ts.api.module.channel.entity.po.ChannelFlowConfigPO;
import com.ts.api.module.channel.service.ChannelConfigService;
import com.ts.api.module.common.entity.DistrictPO;
import com.ts.api.module.common.entity.bo.IpInfoBO;
import com.ts.api.module.common.service.IpInfoService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ChannelConfigServiceImpl implements ChannelConfigService {

    @Autowired
    private ChannelConfigDao channelConfigDao;
    @Autowired
    private ChannelConfigIpOffModuleDao channelConfigIpOffModuleDao;
    @Autowired
    private IpInfoService ipInfoService;

    @Override
    @Transactional(readOnly = true)
    public ChannelFlowConfigPO getFlowConfigByChannelId() {
        Long id = ChannelContext.getId();
        return channelConfigDao.getFlowConfigByChannelId(id);
    }

    @Override
    @Transactional(readOnly = true)
    public boolean hasIpOffModule() {
        if (ChannelTypeEnum.APP.hasType()) {
            ChannelFlowConfigPO channelFlowConfigPO = this.getFlowConfigByChannelId();
            if (SwitchEnum.hasEnable(channelFlowConfigPO.getEnableIpOffModule())) {
                // 获取ip地区
                String ip = ChannelRequestContext.get().getIp();
                IpInfoBO ipInfoBO = ipInfoService.getByIp(ip);
                String cityName = ipInfoBO.getCity();
                DistrictPO districtPO = DistrictCache.getByName(cityName);

                if (ValidParam.isNotNull(districtPO)) {
                    int hasExist = channelConfigIpOffModuleDao.countByAreaCode(ChannelContext.getId(), districtPO.getCode());
                    if (hasExist > 0) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
